<template>
  <Card>
    <Row type="flex"
         align="top"
         justify="space-between">
      <Form ref="formSearch"
            class="sellPending"
            inline>
        <FormItem label="场馆"
                  v-if="!userInfo.storeId">
          <Select v-model="formSearch.storeId"
                  style="width:150px"
                  clearable>
            <Option v-for="(item, index) in storeIdList"
                    :key="index"
                    :value="item.id">{{item.storeName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="卡名称">
          <Select v-model="formSearch.cardName"
                  style="width:200px"
                  filterable
                  remote
                  clearable
                  :remote-method="remoteMethod1"
                  :loading="loading1"
                  placeholder="输入卡名称筛选">
            <Option v-for="(option, index) in options1"
                    :value="option.value"
                    :key="index">{{option.label}}</Option>
          </Select>
        </FormItem>
        <!-- <FormItem label="卡状态">
          <Select @on-change="formSearchState"
                  style="width:200px">
            <Option value="0">全部</Option>
            <Option value="1">激活</Option>
            <Option value="2">未激活</Option>
          </Select>
        </FormItem> -->
        <FormItem label="手机/姓名">
          <Row>
            <Col span="18">
            <Input clearable
                   placeholder="输入手机/姓名搜索"
                   class="search-input"
                   v-model="formSearch.member" />
            </Col>
            <Col span="4"
                 offset="1">
            <Button @click="memberCardList"
                    class="search-btn"
                    type="primary">
              <Icon type="search" />搜索</Button>
            </Col>
          </Row>

        </FormItem>
      </Form>
      <Button class="margin-b-20"
              icon="md-add"
              type="primary"
              @click="expenseModal = true">发卡</Button>
    </Row>
    <Table border
           :loading="tableLoading"
           :columns="expenseListColumns"
           :data="expenseColumns">
    </Table>
    <Row type="flex"
         class="margin-t-20">
      <Page :total="pageTotal"
            @on-change="changePage" />
    </Row>
    <Modal v-model="expenseModal"
           title="发卡"
           :loading="loading"
           :mask-closable="false"
           @on-ok="onExpenseSubmit"
           @on-visible-change="onAddExpenseVisible">
      <Form :model="expense"
            ref="expenseForm"
            :rules="ruleValidate"
            :label-width="100">
        <FormItem label="手机"
                  prop="phone">
          <Input v-model="expense.phone"
                 style="width:250px"
                 search
                 enter-button
                 @on-search="getByPhone"
                 placeholder="输入手机号码查找用户信息" />
          <span class="demo-data">{{seachText}}</span>
        </FormItem>
        <FormItem label="场馆"
                  v-if="!userInfo.storeId">
          <Select v-model="expense.storeId"
                  @on-change="getStaffList"
                  style="width:250px"
                  clearable>
            <Option v-for="(item, index) in storeIdList"
                    :key="index"
                    :value="item.id">{{item.storeName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="发卡员"
                  prop="sendCardUser">
          <Select v-model="expense.sendCardUser"
                  style="width:250px"
                  clearable>
            <Option v-for="(item, index) in staffList"
                    :key="index"
                    :value="item.nickname">{{item.nickname}}</Option>
          </Select>
        </FormItem>
        <FormItem label="卡名称"
                  prop="cardId">
          <Select v-model="expense.cardId"
                  @on-change="changeCardType"
                  filterable
                  remote
                  :remote-method="remoteMethod1"
                  :loading="loading1"
                  style="width:250px">
            <Option v-for="item in options1"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="发卡时间"
                  prop="sendTimeStr">
          <DatePicker v-model="expense.sendTimeStr"
                      @on-change="changeSendTime"
                      type="date"
                      placeholder="会员卡发卡时间"
                      style="width: 250px"></DatePicker>
        </FormItem>
        <FormItem label="激活时间">
          <DatePicker v-model="expense.startTimeStr"
                      @on-change="changeStartTime"
                      type="date"
                      placeholder="会员卡激活时间"
                      style="width: 250px"></DatePicker>
        </FormItem>
        <FormItem label="过期时间">
          <DatePicker v-model="expense.endTimeStr"
                      @on-change="changeEndTime"
                      type="date"
                      placeholder="会员卡过期时间"
                      style="width: 250px"></DatePicker>
        </FormItem>
        <FormItem label="交费总额"
                  prop="price">
          <Input v-model="expense.price"
                 style="width: 250px;"></Input>
        </FormItem>
        <FormItem label="可消费"
                  v-if="expense.consumptionType !== 3">
          <Input v-model="expense.count"
                 @on-blur="blurCount"
                 style="width: 250px;">
          <div slot="append">
            <span v-if="expense.consumptionType === 1">天</span>
            <span v-if="expense.consumptionType === 2">次</span>
            <span v-if="expense.consumptionType === 3">元</span>
          </div>
          </Input>
        </FormItem>
        <FormItem label="状态">
          <i-switch size="large"
                    v-model="expense.state">
            <span slot="open">激活</span>
            <span slot="close">未激活</span>
          </i-switch>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="expense.remarks"
                 clearable
                 maxlength="100"
                 show-word-limit
                 type="textarea"
                 placeholder="请输入备注"
                 style="width: 250px" />
        </FormItem>
      </Form>
    </Modal>

    <Modal v-model="editModal"
           title="编辑"
           :loading="loading"
           :mask-closable="false"
           @on-ok="onEditSubmit"
           @on-visible-change="onAddExpenseVisible">
      <Form :model="edit"
            ref="editForm"
            :label-width="100">
        <FormItem label="手机">
          <Input v-model="edit.phone"
                 disabled
                 style="width:250px" />
        </FormItem>
        <FormItem label="场馆">
          <Input v-model="edit.storeName"
                 disabled
                 style="width:250px" />
        </FormItem>
        <FormItem label="发卡员">
          <Input v-model="edit.sendCardUser"
                 disabled
                 style="width:250px" />
        </FormItem>
        <FormItem label="卡名称">
          <Input v-model="edit.cardName"
                 disabled
                 style="width:250px" />
        </FormItem>
        <FormItem label="发卡时间">
          <div>{{edit.sendTime}}</div>
        </FormItem>
        <FormItem label="激活时间">
          <DatePicker v-model="edit.startTimeStr"
                      @on-change="changeEditStartTime"
                      type="date"
                      placeholder="会员卡激活时间"
                      style="width: 250px"></DatePicker>
        </FormItem>
        <FormItem label="过期时间">
          <DatePicker v-model="edit.endTimeStr"
                      @on-change="changeEditEndTime"
                      type="date"
                      placeholder="会员卡过期时间"
                      style="width: 250px"></DatePicker>
        </FormItem>
        <FormItem label="交费总额"
                  prop="price">
          <Input v-model="edit.price"
                 disabled
                 style="width: 250px;"></Input>
        </FormItem>
        <FormItem label="可消费">
          <Input v-model="edit.balance"
                 @on-blur="blurCount2"
                 style="width: 250px;">
          <div slot="append">
            <span v-if="edit.cardType === 1">天</span>
            <span v-if="edit.cardType === 2">次</span>
            <span v-if="edit.cardType === 3">元</span>
          </div>
          </Input>
        </FormItem>
        <FormItem label="状态">
          <i-switch size="large"
                    v-model="edit.state">
            <span slot="open">激活</span>
            <span slot="close">未激活</span>
          </i-switch>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="edit.remarks"
                 clearable
                 maxlength="100"
                 show-word-limit
                 type="textarea"
                 placeholder="请输入备注"
                 style="width: 250px" />
        </FormItem>
      </Form>
    </Modal>
    <Modal title="会员详情"
           :mask-closable="false"
           fullscreen
           scrollable
           v-model="detailsModal">
      <member-details ref="detailsModal"></member-details>
      <div slot="footer">
        <Button type="error"
                size="large"
                long
                @click="detailsModal = false">关闭</Button>
      </div>
    </Modal>
  </Card>

</template>
<script>
import memberDetails from './components/member-details'
// import { expenseList, addExpense, deleteExpense } from '@/api/expense'
import { addMemberCard, memberCardList, deleteMemberCard, updateCard } from '@/api/card'
import { getByPhone } from '@/api/user'
import { cardList } from '@/api/setting-course'
import { storeAll } from '@/api/setting-shop'
import { staffList } from '@/api/setting-staff'
import { mapGetters } from 'vuex'
import { formatDateTime } from '@/libs/util'
export default {
  components: {
    memberDetails
  },
  data () {
    return {
      detailsModal: false,
      expenseModal: false,
      loading: true,
      tableLoading: false,
      // 弹框
      expense: {
        phone: '',
        storeId: 0,
        sendCardUser: '',
        count: 0,
        cardId: '',
        price: '',
        startTime: '',
        startTimeStr: '',
        sendTime: '',
        sendTimeStr: '',
        endTime: '',
        endTimeStr: '',
        consumption: 0,
        consumptionType: 1,
        remarks: '',
        state: true
      },
      // 场馆列表
      storeIdList: [],
      // 店员列表
      staffList: [],
      // 会员卡列表
      cardNameList: [],
      // 会员卡对象
      cardNameObj: {},
      // 消费会员卡信息
      seachInfoCards: [],
      seachText: '',
      ruleValidate: {
        price: [{ required: true, message: '请输入卡的交费总额', trigger: 'blur' }],
        cardId: [{ required: true, type: 'number', message: '请输入会员卡名称', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        consumption: [{ required: true, message: '请输入消费金额/次数', trigger: 'blur' }]
      },
      pageTotal: 0,
      expenseListColumns: [
        {
          title: '姓名',
          key: 'name',
          fixed: 'left',
          minWidth: 100
        },
        {
          title: '电话',
          key: 'phone',
          minWidth: 140
        },
        {
          title: '发卡馆',
          key: 'storeName',
          minWidth: 140
        },
        {
          title: '卡名称',
          key: 'cardName',
          minWidth: 140
        },
        {
          title: '卡价值(元)',
          key: 'price',
          minWidth: 120
        },
        {
          title: '卡余额',
          key: 'balance',
          minWidth: 140,
          render: (h, params) => {
            let ut = ''
            switch (params.row.cardType) {
              case 1:
                ut = '天'
                break
              case 2:
                ut = '次'
                break
              case 3:
                ut = '元'
                break
            }
            return h('span', {
              style: {
              }
            }, params.row.balance + ut)
          }
        },
        {
          title: '操作人',
          key: 'sendCardUser',
          minWidth: 100
        },
        {
          title: '发卡时间',
          key: 'sendTime',
          minWidth: 140,
          render: (h, params) => {
            return h('span', {
              style: {
              }
            }, formatDateTime(params.row.sendTime))
          }
        },
        {
          title: '激活时间',
          key: 'startTime',
          minWidth: 140,
          render: (h, params) => {
            return h('span', {
              style: {
              }
            }, formatDateTime(params.row.startTime))
          }
        },
        {
          title: '到期时间',
          key: 'endTime',
          minWidth: 140,
          render: (h, params) => {
            return h('span', {
              style: {
              }
            }, formatDateTime(params.row.endTime))
          }
        },
        {
          title: '备注',
          key: 'remarks',
          minWidth: 140
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          fixed: 'right',
          align: 'center',
          render: (h, params) => {
            const arr = [h('Button', {
              props: {
                type: 'primary',
                size: 'small'
              },
              style: {
                marginRight: '5px'
              },
              on: {
                click: () => {
                  this.detailsModal = true
                  this.$refs.detailsModal.getByPhone(params.row.phone)
                }
              }
            }, '详情'),
            h('Button', {
              props: {
                type: 'error',
                size: 'small'
              },
              on: {
                click: () => {
                  this.deleteMemberCard(params.row.id)
                }
              }
            }, '删除')]
            if (!params.row.state) {
              arr.push(h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginLeft: '5px'
                },
                on: {
                  click: () => {
                    this.editShowModal(params.row)
                  }
                }
              }, '编辑'))
            }
            return h('div', arr)
          }
        }
      ],
      expenseColumns: [],
      // 筛选条件
      formSearch: {
        cardName: '',
        size: 10,
        page: 1,
        member: '',
        storeId: 0
      },
      model13: '',
      loading1: false,
      options1: [],
      list: [],
      reseIndex: 0,
      startValue: '',
      endValue: '',
      // 编辑
      editModal: false,
      edit: {
        cardType: 1
      }
    }
  },
  computed: {
    formatStartNumber () {
      if (this.startValue === '') return '请输入金额'
      function parseNumber (str) {
        const re = /\d{1,3}(?=(\d{3})+(\.|$))/g
        return str.replace(re, '$&,')
      }
      return parseNumber(this.startValue)
    },
    formatEndNumber () {
      if (this.endValue === '') return '请输入金额'
      function parseNumber (str) {
        const re = /\d{1,3}(?=(\d{3})+(\.|$))/g
        return str.replace(re, '$&,')
      }
      return parseNumber(this.endValue)
    },
    ...mapGetters([
      'userInfo'
    ])
  },
  async created () {
    if (this.userInfo.storeId) {
      this.$set(this.expense, 'storeId', this.userInfo.storeId)
      this.$set(this.formSearch, 'storeId', this.userInfo.storeId)
    }
    this.tableLoading = true
    await this.cardList()
    await this.getStaffList()
    await this.storeAll()
    await this.memberCardList()
  },
  methods: {
    editShowModal (info) {
      if (info) {
        info.sendTime = formatDateTime(info.sendTime)
        info.sendTimeStr = formatDateTime(info.sendTime)
        info.startTime = formatDateTime(info.startTime)
        info.startTimeStr = formatDateTime(info.startTime)
        info.endTime = formatDateTime(info.endTime)
        info.endTimeStr = formatDateTime(info.endTime)
        this.edit = { ...info }
      }
      this.editModal = true
    },
    storeAll () { // 场馆列表
      return new Promise((resolve, reject) => {
        storeAll().then(res => {
          this.storeIdList = res.data
          resolve(res.data)
        })
      })
    },
    getStaffList () { // 店员列表
      return new Promise((resolve, reject) => {
        staffList({ size: 200, storeId: this.expense.storeId }).then(res => {
          this.staffList = res.data.rows
          resolve(res.data.rows)
        })
      })
    },
    cardList () { // 卡列表
      cardList({
        name: '',
        type: '',
        varieties: ''
      }).then(res => {
        this.cardNameList = res.data
        res.data.forEach(e => {
          this.cardNameObj['card' + e.id] = e
        })
      })
    },
    memberCardList () {
      this.tableLoading = true
      this.formSearch.storeId = this.formSearch.storeId || 0
      memberCardList(this.formSearch).then(res => {
        this.expenseColumns = res.data.records
        this.pageTotal = res.data.total
        this.tableLoading = false
      })
    },
    onAddExpenseVisible (visible) {
      // 弹框状态改变 清除默认值
      if (visible) return
      this.$refs['expenseForm'].resetFields()
      this.$refs['editForm'].resetFields()
    },
    onExpenseSubmit () {
      this.$refs['expenseForm'].validate(valid => {
        console.log(this.expense)
        // eslint-disable-next-line no-useless-return
        setTimeout(() => {
          this.loading = false
        }, 300)
        setTimeout(() => {
          this.loading = true
        }, 400)
        if (!valid) return
        addMemberCard(this.expense).then(res => {
          this.$refs['expenseForm'].resetFields()
          this.expenseModal = false
          this.$Message.success('添加成功')
          this.memberCardList()
        })
      })
    },
    onEditSubmit () {
      this.$refs['editForm'].validate(valid => {
        // eslint-disable-next-line no-useless-return
        setTimeout(() => {
          this.loading = false
        }, 300)
        setTimeout(() => {
          this.loading = true
        }, 400)
        if (!valid) return
        updateCard(this.edit).then(res => {
          this.$refs['editForm'].resetFields()
          this.editModal = false
          this.$Message.success('修改成功')
          this.memberCardList()
        })
      })
    },
    deleteMemberCard (id) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除？',
        loading: true,
        okText: '删除',
        onOk: () => {
          deleteMemberCard(id)
            .then(res => {
              this.$Modal.remove()
              this.$Message.success('删除成功')
              this.memberCardList()
            })
            .catch(() => {
              this.$Modal.remove()
            })
        }
      })
    },
    remoteMethod1 (query) {
      if (query !== '') {
        this.loading1 = true
        setTimeout(() => {
          this.loading1 = false
          const cardNameList = this.cardNameList.map(item => {
            return {
              value: item.id,
              label: item.name,
              type: item.type
            }
          })
          this.options1 = cardNameList.filter(item => item.label.toLowerCase().indexOf(query.toLowerCase()) > -1)
        }, 200)
      } else {
        this.options2 = []
      }
    },
    getByPhone (val) {
      this.seachText = '正在查询...'
      getByPhone(val).then(res => {
        this.seachText = res.data.realname
        this.seachInfoCards = res.data.cards
      }).catch(() => {
        this.seachText = '查询失败'
      })
    },
    changeCardType (item) { // 根据卡名称判断消费类型
      const type = this.cardNameObj['card' + item].type
      if (type !== 1) {
        this.$set(this.expense, 'endTimeStr', '2099-01-01')
        this.$set(this.expense, 'endTime', '2099-01-01')
      } else {
        this.$set(this.expense, 'endTimeStr', '')
        this.$set(this.expense, 'endTime', '')
      }
      this.$set(this.expense, 'consumptionType', type)
      this.$set(this.expense, 'count', 0)
      this.$set(this.expense, 'cardName', this.cardNameObj['card' + item].name)
    },
    changePage (val) {
      this.formSearch = { ...this.formSearch, page: val }
      this.memberCardList()
    },
    formSearchState (state) {
      let stateVal = ''
      switch (state) {
        case '0':
          stateVal = ''
          break
        case '1':
          stateVal = true
          break
        case '2':
          stateVal = false
          break
      }
      this.formSearch.state = stateVal
    },
    changeState (state) { // 卡状态
      this.$set(this.expense, 'state', state ? 1 : 0)
    },
    changeSendTime (e) {
      this.expense.sendTime = e
    },
    changeEditStartTime (e) {
      this.edit.startTime = e
    },
    changeEditEndTime (e) {
      this.edit.endTime = e
      this.DateDiff(this.edit.startTime, e)
    },
    changeStartTime (e) {
      this.expense.startTime = e
    },
    changeEndTime (e) {
      this.expense.endTime = e
      this.DateDiff(this.expense.sendTime, e)
    },
    blurCount2 () {
      if (this.edit.cardType === 2) return
      console.log(this.edit.balance)
      this.DateDiffDay(this.edit.balance, this.edit.startTime)
    },
    blurCount () {
      if (this.expense.consumptionType === 2) return
      this.DateDiffDay(this.expense.count, this.expense.startTime)
    },
    DateDiff (sDate1, sDate2) { // 开始时间 -- 结束时间 计算天数
      const d1 = new Date(sDate2.replace(/-/g, '/'))
      const d2 = new Date(sDate1.replace(/-/g, '/'))
      const ms = Math.abs(d2.getTime() - d1.getTime())// 毫秒
      const d = ms / 1000 / 60 / 60 / 24// 转为天
      this.expense.count = d
      this.edit.balance = d
    },
    DateDiffDay (days, time) { // 可消费天数转日期
      if (!time) return
      let dateTemp = new Date(time.replace(/-/g, '/')).getTime() || +new Date()
      var millSeconds = dateTemp + (days * 24 * 60 * 60 * 1000)
      var rDate = new Date(millSeconds)
      var year = rDate.getFullYear()
      var month = rDate.getMonth() + 1
      if (month < 10) month = '0' + month
      var date = rDate.getDate()
      if (date < 10) date = '0' + date
      this.$set(this.expense, 'endTimeStr', (year + '-' + month + '-' + date))
      this.$set(this.expense, 'endTime', (year + '-' + month + '-' + date))
      this.$set(this.edit, 'endTimeStr', (year + '-' + month + '-' + date))
      this.$set(this.edit, 'endTime', (year + '-' + month + '-' + date))
    }
  }
}
</script>
<style lang="less">
.sellPending {
  flex: 1;
  .search-item {
    display: flex;
    margin-bottom: 10px;
    .search-btn {
      margin-left: 20px;
    }
  }
}
.receiverTypeTip {
  text-align: center;
  overflow: hidden;
  &-title {
    margin-bottom: 5px;
  }
  &-img {
    width: 200px;
    overflow: hidden;
    img {
      width: 100%;
      height: auto;
    }
  }
}
.confirmRemberModalRow {
  margin-bottom: 10px;
}
.loading-drop-down {
  display: flex;
  align-items: center;
  padding: 2px 16px;
  background-color: #f2f6fa;
  color: #357ce1;
  border-radius: 2px;
}
.ivu-switch-large {
  width: 66px;
}
</style>
